package com.kpx.app.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.kpx.app.R;
import com.kpx.app.adapter.OrderLogAdapter;
import com.kpx.app.adapter.PicAdapter;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.bean.OrderBean;
import com.kpx.app.bean.OrderDetailBean;
import com.kpx.app.configs.BroadcastFilters;
import com.kpx.app.configs.Constants;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.ResObj;
import com.kpx.app.thirdparty.wechat.utils.WechatConstants;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.OrderUtils;
import com.kpx.app.utils.TimeUtil;
import com.kpx.app.utils.UIUtils;
import com.kpx.app.utils.UserInfoUtils;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.view.TitleView;
import com.kpx.app.wigdet.AutoSizeGridView;
import com.kpx.app.wigdet.AutoSizeListView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by congdy on 17/4/16.
 */

public class ActivityOrderDetail extends ActivityBase {
    public static int inType = 1;//1正常进入2微信支付返回展示
    @BindView(R.id.titleview)
    TitleView titleview;
    @BindView(R.id.img_status)
    ImageView imgStatus;
    @BindView(R.id.txt_order_status)
    TextView txtOrderStatus;
    @BindView(R.id.txt_name)
    TextView txtName;
    @BindView(R.id.txt_phone)
    TextView txtPhone;
    @BindView(R.id.txt_address)
    TextView txtAddress;
    @BindView(R.id.ll_show_address)
    LinearLayout llShowAddress;
    @BindView(R.id.img_task)
    ImageView imgTask;
    @BindView(R.id.txt_pro_name)
    TextView txtProName;
    @BindView(R.id.txt_sex)
    TextView txtSex;
    @BindView(R.id.txt_age)
    TextView txtAge;
    @BindView(R.id.txt_height)
    TextView txtHeight;
    @BindView(R.id.txt_weight)
    TextView txtWeight;
    @BindView(R.id.txt_danbao_price)
    TextView txtDanbaoPrice;
    @BindView(R.id.txt_yongjin_price)
    TextView txtYongjinPrice;
    @BindView(R.id.txt_task_ask)
    TextView txtTaskAsk;
    @BindView(R.id.btn_1)
    Button btn1;
    @BindView(R.id.btn_2)
    Button btn2;
    @BindView(R.id.aglist_pics)
    AutoSizeGridView aglistPics;
    @BindView(R.id.lv_orderlogs)
    AutoSizeListView lv_orderlogs;
    @BindView(R.id.ll_pics)
    LinearLayout llPics;
    @BindView(R.id.sv_content)
    ScrollView sv_content;
    @BindView(R.id.btn_3)
    Button btn3;
    @BindView(R.id.txt_fail_msg)
    TextView txtFailMsg;
    @BindView(R.id.ll_btn)
    LinearLayout llBtn;
    @BindView(R.id.ll_show_sk)
    LinearLayout ll_show_sk;
    @BindView(R.id.txt_request1)
    TextView txtRequest1;
    @BindView(R.id.txt_request3)
    TextView txtRequest3;
    @BindView(R.id.txt_request4)
    TextView txtRequest4;
    @BindView(R.id.txt_request5)
    TextView txtRequest5;
    @BindView(R.id.img_show)
    ImageView img_show;
    @BindView(R.id.txt_shop)
    TextView txtShop;
    @BindView(R.id.ll_shop)
    LinearLayout llShop;
    @BindView(R.id.txt_app_mention)
    TextView txtAppMention;
    @BindView(R.id.txt_acount)
    TextView txtAcount;
    @BindView(R.id.txt_returnaddress)
    TextView txt_returnaddress;
    @BindView(R.id.txt_order_time)
    TextView txtOrderTime;
    @BindView(R.id.ll_flow_show)
    LinearLayout llFlowShow;
    @BindView(R.id.txt_sp_requests)
    TextView txtSpRequests;
    @BindView(R.id.aglist_sp_pics)
    AutoSizeGridView aglistSpPics;
    @BindView(R.id.txt_yj)
    TextView txtYj;
    @BindView(R.id.ll_acount)
    LinearLayout llAcount;
    @BindView(R.id.ll_time)
    LinearLayout llTime;
    @BindView(R.id.txt_sp_requests2)
    TextView txtSpRequests2;
    @BindView(R.id.txt_search)
    TextView txtSearch;
    @BindView(R.id.txt_copy)
    TextView txtCopy;
    @BindView(R.id.ll_show_tb_code)
    LinearLayout llShowTbCode;
    @BindView(R.id.txt_zg_price)
    TextView txtZgPrice;
    @BindView(R.id.ll_zg_show)
    LinearLayout llZgShow;
    @BindView(R.id.txt_star)
    TextView txtStar;
    @BindView(R.id.txt_shose_size)
    TextView txtShoseSize;
    @BindView(R.id.txt_search_content)
    TextView txtSearchContent;
    @BindView(R.id.ll_task_request)
    LinearLayout llTaskRequest;
    @BindView(R.id.ll_flow_request)
    LinearLayout llFlowRequest;
    @BindView(R.id.ll_sk_tk_req)
    LinearLayout llSkTkReq;
    private OrderBean b;
    private OrderDetailBean detailbean;
    private List<OrderDetailBean.PhotosListBean> list = new ArrayList<>();
    private List<OrderDetailBean.OrderlogListBean> loglist = new ArrayList<>();
    private PicAdapter adapter;
    private OrderLogAdapter logAdapter;

    @Override
    public void initview(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_order_detail);
        ButterKnife.bind(this);
        UIUtils.setNormalTitle(titleview, "订单详情");
        adapter = new PicAdapter(this, list, R.layout.item_pic_show);
        aglistPics.setAdapter(adapter);
        logAdapter = new OrderLogAdapter(this, loglist, R.layout.item_order_log_show);
        lv_orderlogs.setAdapter(logAdapter);
        txtCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (b != null && !TextUtils.isEmpty(b.getTaokoulingStr())) {
                    UIUtils.copy(ActivityOrderDetail.this, b.getTaokoulingStr());
                }
            }
        });
    }

    @Override
    public void initData() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (inType == 1) {
            b = (OrderBean) getIntent().getExtras().getSerializable(Constants.KEY_ORDER_BEAN);
            if (b != null) {
                btn1.setVisibility(View.GONE);
                btn2.setVisibility(View.GONE);
                btn3.setVisibility(View.GONE);
                setOrderStatusShow(b);
                getOrderDetail(b.getDmId());
            }
        } else if (inType == 2) {
            getOrderDetail(WechatConstants.ORDER_ID);
        }
    }

    /**
     * 设置订单状态展示
     */
    private void setOrderStatusShow(OrderBean b) {
        OrderUtils.setBtnStatus(this, b, btn1, btn2, btn3, txtOrderStatus);
        imgStatus.setVisibility(View.GONE);
        txtSpRequests2.setVisibility(View.GONE);
//        llZgShow.setVisibility(View.INVISIBLE);
        llShowAddress.setVisibility(View.GONE);
        findViewById(R.id.ll_sp_pics).setVisibility(View.GONE);
        findViewById(R.id.ll_show_address).setVisibility(View.GONE);
        switch (b.getOrderStatus()) {
            case OrderBean.ORDER_STATUS_COMPLETED_WATTING_PRICE://已完成-->评价
                break;
            case OrderBean.ORDER_STATUS_COMPLETED_HAD_PRICE://已完成-->查看评价
                break;
            case OrderBean.ORDER_STATUS_WAITTING_GET://待收货-->查看物流，确认收货
                llShowAddress.setVisibility(View.VISIBLE);
                break;
            case OrderBean.ORDER_STATUS_WAITTING_SEND://待发货-->提醒商家发货
                llShowAddress.setVisibility(View.VISIBLE);
                imgStatus.setVisibility(View.VISIBLE);
                imgStatus.setBackgroundResource(R.drawable.mine_order_watting_send);
                break;
            case OrderBean.ORDER_STATUS_WAITTING_PAY://待支付-->取消订单，去支付
                imgStatus.setVisibility(View.VISIBLE);
                imgStatus.setBackgroundResource(R.drawable.mine_order_watting_pay);
                break;
            case OrderBean.ORDER_STATUS_WAITTING_UPLOAD://待上传-->上传图片
                imgStatus.setVisibility(View.VISIBLE);
                imgStatus.setBackgroundResource(R.drawable.mine_order_watting_upload);
                break;
            case OrderBean.ORDER_STATUS_CLOSED://已关闭-->查看订单
                break;
            case OrderBean.ORDER_STATUS_WATTING_CHECK://
                imgStatus.setVisibility(View.VISIBLE);
                imgStatus.setBackgroundResource(R.drawable.mine_order_watting_checked);
                break;
            case OrderBean.ORDER_STATUS_WATTING_BACK://
                imgStatus.setVisibility(View.VISIBLE);
                imgStatus.setBackgroundResource(R.drawable.mine_order_watting_back);
//                if (b != null && b.getOrderType() != 2) {//1：佣金，2：赠送实物
//                    txtZgPrice.setText(b.getPurchaseAmount() + "");
//                    llZgShow.setVisibility(View.VISIBLE);
//                }
                break;
            case OrderBean.ORDER_STATUS_REFUESD_BY_PINTAI://
            case OrderBean.ORDER_STATUS_REFUESD_BY_SELLER://
                imgStatus.setVisibility(View.VISIBLE);
                imgStatus.setBackgroundResource(R.drawable.mine_order_watting_upload);
                if (!UIUtils.isEmpty(b.getRemark())) {
                    findViewById(R.id.ll_fail_msg).setVisibility(View.VISIBLE);
                    txtFailMsg.setText("  驳回原因：" + b.getRemark());
                }
                break;
            case OrderBean.ORDER_STATUS_WATTING_SP://待收评
                findViewById(R.id.ll_sp_pics).setVisibility(View.VISIBLE);
                break;
            case OrderBean.ORDER_STATUS_SURE_SP://待收评审核
                break;
            case OrderBean.ORDER_STATUS_WAITTING_FILL://待收评审核
                txtSpRequests2.setVisibility(View.VISIBLE);
                txtSpRequests2.setText("注：抢单成功后请使用已绑定的账号，在2小时内至第三方平台下单并提交第三方订单号，否则该单将被取消。");
                break;
        }

    }

    private String getSex(OrderDetailBean.RequirementMapBean sex) {
        if (sex == null) {
            return "不限";
        }
        switch (sex.getSex()) {
            case 0:
                return "不限";
            case 1:
                return "男";
            case 2:
                return "女";
            default:
                return "不限";
        }
    }

    /**
     * 获取订单详情
     */
    private void getOrderDetail(long dmid) {
        showLoadingDialog();
        MyHashMap map = new MyHashMap();
        map.put("orderId", dmid + "");
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    OrderDetailBean bd = (OrderDetailBean) result.getData();
                    if (bd != null) {
                        ActivityOrderDetail.this.detailbean = bd;
                        if (b != null && b.getOrderFlloww() == 2) {//刷拍展示的相关内容
                            llFlowShow.setVisibility(bd.getOrderStatus() == OrderBean.ORDER_STATUS_WAITTING_FILL ? View.VISIBLE : View.GONE);
                            llTaskRequest.setVisibility(View.GONE);
                            ll_show_sk.setVisibility(View.VISIBLE);
                            llFlowRequest.setVisibility(View.GONE);
                            llSkTkReq.setVisibility(bd.getOrderStatus() == OrderBean.ORDER_STATUS_WAITTING_FILL ? View.VISIBLE : View.GONE);
//                            llFlowRequest.setVisibility(bd.getOrderStatus() == OrderBean.ORDER_STATUS_WAITTING_FILL ? View.VISIBLE : View.GONE);
                            txtRequest3.setText(TextUtils.isEmpty(detailbean.getPostageString()) ? "-" : detailbean.getPostageString());
                            txtRequest1.setText(TextUtils.isEmpty(detailbean.getBrushRequirement()) ? "-" : detailbean.getBrushRequirement());
                            if (!TextUtils.isEmpty(detailbean.getTaskTips())) {
                                String tasktips = detailbean.getTaskTips();
                                if (tasktips.contains("：")) {
                                    String[] tips = tasktips.split("\n");
                                    ArrayList<String> strs = new ArrayList<String>();
                                    for (int i = 0; i < tips.length; i++) {
                                        if (tips[i].contains("：")) {
                                            strs.add(tips[i].substring(tips[i].lastIndexOf("：") + 1, tips[i].length()));
                                        }
                                    }
                                    UIUtils.setColorText3(ActivityOrderDetail.this, txtRequest4, strs, R.color.red_FF4088, detailbean.getTaskTips());
                                } else {
                                    txtRequest4.setText(tasktips);
                                }
                            }
                            txtRequest5.setText(TextUtils.isEmpty(detailbean.getRequirementTxt()) ? "-" : detailbean.getRequirementTxt());
                            if (!TextUtils.isEmpty(detailbean.getBrushWorkflowPic())) {
                                Glide.with(ActivityOrderDetail.this).load(detailbean.getBrushWorkflowPic()).into(img_show);
                            }
                            if (!UIUtils.isEmpty(detailbean.getSellerName())) {
                                llShop.setVisibility(View.VISIBLE);
                                txtShop.setText("\"" + detailbean.getSellerName() + "\"");
                            }
                            if (!UIUtils.isEmpty(b.getThirdAccount())) {
                                txtAcount.setText("\"" + b.getThirdAccount() + "\"");
                            }
                            txtOrderTime.setText(TimeUtil.getFormatTime(b.getFinishedTime(), TimeUtil.FORMAT_TIME_MINUTES_TWO));
                            if (b.getOrderStatus() == OrderBean.ORDER_STATUS_WAITTING_FILL && !UIUtils.isEmpty(b.getRemark()) && b.getThirdOrderInfoStatus() == 2) {
                                findViewById(R.id.ll_fail_msg).setVisibility(View.VISIBLE);
                                txtFailMsg.setText("  驳回原因：" + b.getRemark());
                            }
                        }
                        b = bd.copy(b);
                        btn1.setVisibility(View.GONE);
                        btn2.setVisibility(View.GONE);
                        btn3.setVisibility(View.GONE);
                        setOrderStatusShow(b);
                        loglist.clear();
                        OrderDetailBean.OrderlogListBean logOid = new OrderDetailBean.OrderlogListBean();
                        logOid.setDmId(b.getDmId());
                        logOid.setTimeStr("订单编号");
                        loglist.add(logOid);
                        for (int i = 0; i < bd.getOrderlogList().size(); i++) {
                            if (!TextUtils.isEmpty(bd.getOrderlogList().get(i).getTimeStr())) {
                                loglist.add(bd.getOrderlogList().get(i));
                            }
                        }
                        logAdapter.setData(loglist);
                        setData();

                    }
                } else {
                    ToastUtil.getInstance().showToast(ActivityOrderDetail.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog();
                ToastUtil.getInstance().showToast(ActivityOrderDetail.this, error);
            }

        }, OrderDetailBean.class, HttpDataRequest.TYPE_OBJECT).POST(HttpDataReqUrl.URL_POST_ORDER_DETAIL, true, map);
    }

    private void setData() {
        if (OrderBean.ORDER_STATUS_WAITTING_FILL == detailbean.getOrderStatus()) {
            if (detailbean != null && (!TextUtils.isEmpty(detailbean.getTaokoulingStr()) || !TextUtils.isEmpty(detailbean.getThridPlatSearchKey()))) {
                llShowTbCode.setVisibility((!TextUtils.isEmpty(detailbean.getTaokoulingStr()) || !TextUtils.isEmpty(detailbean.getThridPlatSearchKey())) ? View.VISIBLE : View.GONE);
                txtCopy.setVisibility(!TextUtils.isEmpty(detailbean.getTaokoulingStr()) ? View.VISIBLE : View.GONE);
//            UIUtils.setColorText(this, txtSearch,
//                    !TextUtils.isEmpty(b.getTaokoulingStr()) ? "\"" + b.getTaokoulingStr() + "\"" : "\"" + b.getThridPlatSearchKey() + "\"",
//                    R.color.red_FF4088,
//                    !TextUtils.isEmpty(b.getTaokoulingStr()) ? "淘口令：" : "搜索关键词：");
                txtSearchContent.setText(!TextUtils.isEmpty(detailbean.getTaokoulingStr()) ? "\"" + detailbean.getTaokoulingStr() + "\"" : "\"" + detailbean.getThridPlatSearchKey() + "\"");
                txtSearch.setText(!TextUtils.isEmpty(detailbean.getTaokoulingStr()) ? "淘口令：" : "搜索关键词：");
            }
        } else {
            llShowTbCode.setVisibility(View.GONE);
        }
        txt_returnaddress.setVisibility(View.GONE);
        if (b != null) {//1：佣金，2：赠送实物
            txtZgPrice.setText(b.getPurchaseAmount() + "");
            llZgShow.setVisibility(View.VISIBLE);
        }
        if (b != null && b.getOrderStatus() == OrderBean.ORDER_STATUS_WATTING_BACK && detailbean != null && detailbean.getRefundAddress() != null && !TextUtils.isEmpty(detailbean.getRefundAddress())) {
            txt_returnaddress.setText("退货地址：" + detailbean.getRefundAddress());
            txt_returnaddress.setVisibility(View.VISIBLE);
        }
        if (detailbean != null && b.getOrderStatus() == OrderBean.ORDER_STATUS_WATTING_SP) {
            if (!TextUtils.isEmpty(detailbean.getSellerRequireWarn())) {
                txtSpRequests2.setVisibility(View.VISIBLE);
                txtSpRequests2.setText(detailbean.getSellerRequireWarn());
            }
            if (!TextUtils.isEmpty(detailbean.getSellerRequire())) {
                txtSpRequests.setVisibility(View.VISIBLE);
                txtSpRequests.setText("商家收评要求：" + detailbean.getSellerRequire());
            }
            if (detailbean.getSellerRequirePhotosList() != null && detailbean.getSellerRequirePhotosList().size() > 0) {
                PicAdapter modelAdapter = new PicAdapter(this, detailbean.getSellerRequirePhotosList(), R.layout.item_pic_show);
                aglistSpPics.setAdapter(modelAdapter);
            }
        }
        if (detailbean.getPhotosList() != null && detailbean.getPhotosList().size() > 0) {
            llPics.setVisibility(View.VISIBLE);
            adapter.setData(detailbean.getPhotosList());
        } else {
            llPics.setVisibility(View.GONE);
        }
        txtName.setText("收货人：" + detailbean.getReceiver());
        txtPhone.setText("电话：" + detailbean.getPhone());
        txtAddress.setText("收货地址：" + detailbean.getAddress());
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.ic_launcher)//设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.ic_launcher)  //设置图片加载/解码过程中错误时候显示的图片
                .cacheInMemory(true)//设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)//设置下载的图片是否缓存在SD卡中
                .imageScaleType(ImageScaleType.EXACTLY)//设置图片以如何的编码方式显示
                .build();//不推荐用！！！！是否设置为圆角，弧度为多少
        if (detailbean != null) {
            ImageLoader.getInstance().displayImage(TextUtils.isEmpty(detailbean.getTaskGoods().getMainPic()) ? "--" : detailbean.getTaskGoods().getMainPic(), imgTask, options);
            txtProName.setText(detailbean.getTaskGoods().getGoodsName());
            txtTaskAsk.setText(UIUtils.isEmpty(detailbean.getRequirementTxt()) ? "" : detailbean.getRequirementTxt());
        }
        if (b != null) {
            adapter.setOrderBean(b);
        }
        txtSex.setText("性别：" + getSex(detailbean.getRequirementMap()));
        txtAge.setText("年龄：" + (detailbean.getRequirementMap() == null || UIUtils.isEmptyTask(detailbean.getRequirementMap().getAge()) ? "不限" : (detailbean.getRequirementMap().getAge() + "")));
        txtHeight.setText("身高：" + (detailbean.getRequirementMap() == null || UIUtils.isEmptyTask(detailbean.getRequirementMap().getHeight()) ? "不限" : detailbean.getRequirementMap().getHeight() + ""));
        txtWeight.setText("体重：" + (detailbean.getRequirementMap() == null || UIUtils.isEmptyTask(detailbean.getRequirementMap().getWeight()) ? "不限" : detailbean.getRequirementMap().getWeight() + ""));
        txtStar.setText("等级：" + (detailbean.getRequirementMap() == null || UIUtils.isEmptyTask(detailbean.getRequirementMap().getLevel()) ? "不限" : detailbean.getRequirementMap().getLevel() + ""));
        txtShoseSize.setText("鞋码：" + (detailbean.getRequirementMap() == null || UIUtils.isEmptyTask(detailbean.getRequirementMap().getSize()) ? "不限" : detailbean.getRequirementMap().getSize() + ""));

        txtDanbaoPrice.setText(df.format(detailbean.getDeposit()));
        txtYongjinPrice.setText(b.getOrderType() == 1 ? df.format(detailbean.getCommission()) : "赠送实物");
        findViewById(R.id.txt_yj).setVisibility(b.getOrderType() == 1 ? View.VISIBLE : View.GONE);
        sv_content.scrollTo(0, 0);
    }

    DecimalFormat df = new DecimalFormat("###0.00");

    @Override
    public void onReceiver(Context context, Intent intent) {
        if (intent.getAction().equals(BroadcastFilters.BROADCAST_ACTION_REFRESH_DATA)) {
            finish();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    public void reFreshUpCount(int size) {
        if (size > 0) {
            llPics.setVisibility(View.VISIBLE);
        } else {
            llPics.setVisibility(View.GONE);
        }
        b.setNowPhotosNum(size);
        btn1.setVisibility(View.GONE);
        btn2.setVisibility(View.GONE);
        btn3.setVisibility(View.GONE);
        OrderUtils.setBtnStatus(this, b, btn1, btn2, btn3, txtOrderStatus);
    }
}
